<!-- eslint-disable vue/html-self-closing -->
<template>
  <div class="employees-container">
    <!-- 员工模块 -->
    <div v-loading="loading" class="app-container">
      <!-- 页头 -->
      <PageHearder>
        <template #left>总条数：{{ total }}条</template>
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/employees/upload-excel')"
          >
            Excel导入
          </el-button>
          <el-button type="danger" size="small" @click="handelDownload()">
            Excel下载当前页员工数据
          </el-button>
          <el-button type="danger" size="small" @click="handelDownloadAll">
            下载所有员工Excel数据
          </el-button>
          <el-button type="primary" size="small" @click="showDialog = true">
            新增员工
          </el-button>
        </template>
      </PageHearder>
      <!-- 卡片 -->
      <el-card style="margin-top: 10px">
        <!-- 表格区域 -->
        <!-- 表头 -->
        <el-table :data="empList" width="100%">
          <el-table-column
            label="序号"
            type="index"
            :index="indexMethod"
            width="100"
          />
          <el-table-column label="姓名" prop="username" width="120" />
          <el-table-column label="头像" width="300">
            <template #default="{ row }">
              <img
                v-imgerror="defaultAvatar"
                :src="row.staffPhoto"
                width="80%"
                @click="handelShowCanvas(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" width="120" />
          <el-table-column label="工号" prop="workNumber" width="180" />
          <el-table-column label="聘用形式" width="90">
            <template #default="{ row }">
              <!-- {{ row.formOfEmployment === 1 ? '正式员工' : '实习ing' }} -->
              {{ formmatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" width="110" />
          <el-table-column label="入职时间" prop="timeOfEntry" width="120" />
          <el-table-column label="账户状态" width="110">
            <template #default="{ row }">
              {{ formatEnableState(row.enableState) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="300">
            <template #default="{ row }">
              <el-button
                type="text"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <el-button v-permission="'point-del'" type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button type="text" @click="handelPersonShow(row.id)">
                角色
              </el-button>
              <el-button type="text" @click="handleDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 跳转栏 -->
        <el-pagination
          :total="total"
          :page-size="query.size"
          :current-page="query.page"
          :page-sizes="[3, 5, 8, 10]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </el-card>
      <!-- 新增员工组件 -->
      <add-employee
        :show-dialog.sync="showDialog"
        @add-success="getEmpioyeeList"
      />

      <!-- 二维码弹窗 -->
      <el-dialog :visible="iShow" title="二维码" @close="iShow = false">
        <!-- 展示二维码图片 -->
        <canvas ref="canvas" />
      </el-dialog>

      <!-- 分配角色弹窗 -->
      <el-dialog title="分配角色" :visible="personShow" @close="personClose">
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="item in defauleList"
            :key="item.id"
            :label="item.id"
          >
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
        <template #footer>
          <el-button size="small" @click="personClose">取消</el-button>
          <el-button size="small" type="primary" @click="handelAssgin">
            确定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getEmpioyeeListAPI,
  delEmpolueeAPI,
  getEmplyeeInfoAPI,
  assignRoleAPI
} from '@/api/employees'
import { getRoleListAPI } from '@/api/settings'
// 模块化语法导入默认头像地址
import defaultAvatar from '@/assets/common/el.png'
// 导入常量模块
import empAppoint from '@/constant/employees'
// 局部注册组件
import addEmployee from './components/addEmployee.vue'

import dayjs from 'dayjs'
import Qrcode from 'qrcode'
// Excel文件的导入和导出
import { export_json_to_excel } from '@/vendor/Export2Excel'
// 导入/上传: 把Excel文件中的数据读到内存中, 读出来就是一个数组，基于数组做列表渲染
export default {
  name: 'Employees',
  components: { addEmployee },
  data() {
    return {
      // 默认角色列表
      defauleList: [],
      // 角色列表
      checkList: [],
      // 分配角色弹窗
      personShow: false,
      // 员工列表
      empList: [],
      query: {
        page: 1,
        size: 5
      },
      total: 0,
      // 默认头像地址
      defaultAvatar,
      loading: false,
      // 组件是否显示
      showDialog: false,
      // 二维码弹窗
      iShow: false
    }
  },
  created() {
    this.getEmpioyeeList()
  },
  methods: {
    async handelAssgin() {
      console.log(this.emploId)
      try {
        // 把选中的角色同步到数据库
        const resp = await assignRoleAPI(this.emploId, this.checkList)
        console.log(resp)
        this.personClose()
        this.$message.success('用户角色分配修改成功')
      } catch (error) {
        console.log(error)
        this.$message.error(error.message)
      }
    },
    // 分配角色弹框关闭时
    personClose() {
      this.personShow = false
      this.checkList = []
    },
    // 分配角色弹框打开时
    async handelPersonShow(emploId) {
      this.emploId = emploId
      this.personShow = true
      // 获取所有角色列表
      const resp = await getRoleListAPI({ page: 1, pagesize: this.total })
      // console.log(resp)
      this.defauleList = resp.data.rows

      // 获取当前员工角色信息
      const { data } = await getEmplyeeInfoAPI(emploId)
      console.log(data)
      this.checkList = data.roleIds
    },
    // 获取员工列表
    async getEmpioyeeList() {
      const { data } = await getEmpioyeeListAPI(this.query)
      const { rows, total } = data
      this.empList = rows
      this.total = total
    },
    // 自定义下标
    indexMethod(index) {
      return index + 1 + (this.query.page - 1) * this.query.size
    },
    // 格式化聘用形式
    formmatEmployment(formOfEmployment) {
      const item = empAppoint.hireType.find(
        (item) => item.id === formOfEmployment
      )
      return item ? item.value : '未知'
    },
    // 格式化在职状态
    formatEnableState(state) {
      // 根据enableState去workingState中查找
      const item = empAppoint.workingState.find((item) => item.id === state)
      // 三元:如果找到了，返回对象的value属性; 否则返回未知
      return item ? item.value : '未知'
    },
    // 每页条数改变时
    handleSizeChange(val) {
      // 把选择的条数同步到query.size中
      this.query.size = val
      this.loading = true
      //  获取员工列表
      this.getEmpioyeeList()
      this.loading = false
    },
    // 页码改变时
    handleCurrentChange(val) {
      this.query.page = val
      this.loading = true
      this.getEmpioyeeList()
      this.loading = false
    },
    // 删除员工
    async handleDel(empid) {
      try {
        // 询问
        await this.$confirm('确定删除吗？', '提示', {
          type: 'warning'
        })
        // 如果当前不是第一页，并且EmpioyeeList只有一条数据
        // 需要页码前进一页
        if (this.query.page > 1 && this.empList.length === 1) this.query.page--
        // 确定
        // 发起删除请求Expe
        await delEmpolueeAPI(empid)
        // 获取员工列表Expe
        this.getEmpioyeeList()
        // 给个删除成功的提示
        this.$message.success('删除成功')
        // 取消
      } catch (error) {
        if (error.message) return this.$message.error(error)
      }
    },
    // 下载当前页excel文件
    handelDownload(empList = this.empList) {
      // 表头数组
      const header = [
        '姓名',
        '部门',
        '手机号',
        '工号',
        '聘用形式',
        '入职日期',
        '转正日期'
      ]
      // 中英文键的对应关系
      const en2cnKey = {
        部门: 'departmentName',
        姓名: 'username',
        工号: 'workNumber',
        转正日期: 'correctionTime',
        聘用形式: 'formOfEmployment',
        入职日期: 'timeOfEntry',
        手机号: 'mobile'
      }
      // 处理employeeList，得到二维数组
      const data = empList.map((item) => {
        const arr = []
        // 遍历header数组
        header.forEach((zhKey) => {
          const enKey = en2cnKey[zhKey]
          if (enKey === 'formOfEmployment') {
            const temp = empAppoint.hireType.find(
              (dijia) => dijia.id === item[enKey]
            )
            arr.push(temp ? temp.value : '未知')
          } else {
            // 根据得到的英文key从item中取出属性值
            // 根据得到的英文key从item对象中取属性值，push到arr空数组中
            arr.push(item[enKey])
          }
        })
        return arr
      })
      export_json_to_excel({
        // 表头
        header,
        // 表体
        data,
        // 文件名
        filename: `${dayjs(new Date()).format('YYYY-MM-DD')}第 ${
          this.query.page
        } 页员工数据`
      })
    },
    // 下载所有员工数据
    async handelDownloadAll() {
      const node = {
        page: 1,
        size: this.total
      }
      const { data } = await getEmpioyeeListAPI(node)
      // console.log(data)
      this.handelDownload(data.rows)
    },
    // 显示二维码弹窗
    handelShowCanvas(url) {
      if (!url) return
      this.iShow = true

      this.$nextTick(() => {
        // console.log(this.$refs.canvas)
        Qrcode.toCanvas(this.$refs.canvas, url)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-pagination {
  margin-top: 20px;
}
</style>
